<template>
  <div class="n8n-chat-container">
    <!-- N8N Chat 容器 -->
    <div ref="chatContainer" id="n8n-chat" class="w-full h-full"></div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { createChat } from '@n8n/chat'

interface Props {
  webhookUrl?: string
  mode?: 'window' | 'fullscreen'
  showWelcomeScreen?: boolean
  allowFileUploads?: boolean
  initialMessages?: string[]
  enableStreaming?: boolean
  chatInputKey?: string
  chatSessionKey?: string
  loadPreviousSession?: boolean
  metadata?: Record<string, any>
}

const props = withDefaults(defineProps<Props>(), {
  webhookUrl: 'https://pixeljet-n8n.com/webhook/1d5d76aa-895e-49f9-84ff-f3b6120040e4/chat',
  mode: 'fullscreen',
  showWelcomeScreen: true,
  allowFileUploads: false,
  enableStreaming: true,
  chatInputKey: 'chatInput',
  chatSessionKey: 'sessionId',
  loadPreviousSession: true,
  initialMessages: () => [
    'Hello! I\'m your AI Art Assistant, ready to help you create stunning images!',
    'I specialize in prompt writing, style selection, and technique optimization.',
    'What amazing artwork would you like to create today?'
  ],
  metadata: () => ({})
})

const emit = defineEmits<{
  message: [data: any]
  error: [error: any]
  ready: []
}>()

const chatContainer = ref<HTMLElement>()
let chatInstance: any = null

onMounted(async () => {
  try {
    console.log('Initializing N8N Chat with container:', chatContainer.value)
    
    // 等待DOM元素准备就绪
    await new Promise(resolve => setTimeout(resolve, 200))
    
    if (!chatContainer.value) {
      throw new Error('Chat container not found')
    }
    
    // 完整配置，包含国际化设置
    chatInstance = createChat({
      webhookUrl: props.webhookUrl,
      target: '#n8n-chat',
      mode: props.mode,
      showWelcomeScreen: props.showWelcomeScreen,
      allowFileUploads: props.allowFileUploads,
      initialMessages: props.initialMessages,
      enableStreaming: props.enableStreaming,
      chatInputKey: props.chatInputKey,
      chatSessionKey: props.chatSessionKey,
      loadPreviousSession: props.loadPreviousSession,
      defaultLanguage: 'en',
      metadata: props.metadata,
      i18n: {
        en: {
          title: 'AI Art Assistant',
          subtitle: 'Your creative partner for AI image generation',
          footer: 'Powered by n8n',
          getStarted: 'New Conversation',
          inputPlaceholder: 'Ask me about prompts, styles, or techniques...',
          closeButtonTooltip: 'Close chat',
        }
      },
      // 添加自定义配置
      theme: {
        primaryColor: '#667eea',
        secondaryColor: '#764ba2',
        borderRadius: '0.75rem',
        messageSpacing: '1.25rem',
        animationDuration: '0.3s'
      }
    })
    
    console.log('N8N Chat instance created:', chatInstance)
    
    // 延迟触发ready事件
    setTimeout(() => {
      emit('ready')
    }, 500)
    
  } catch (error) {
    console.error('Failed to initialize N8N Chat:', error)
    emit('error', error)
  }
})

onUnmounted(() => {
  if (chatInstance && typeof chatInstance.destroy === 'function') {
    chatInstance.destroy()
  }
})

// 暴露方法给父组件
defineExpose({
  sendMessage: (message: string) => {
    if (chatInstance && typeof chatInstance.sendMessage === 'function') {
      chatInstance.sendMessage(message)
    }
  },
  clearMessages: () => {
    if (chatInstance && typeof chatInstance.clearMessages === 'function') {
      chatInstance.clearMessages()
    }
  },
  destroy: () => {
    if (chatInstance && typeof chatInstance.destroy === 'function') {
      chatInstance.destroy()
    }
  }
})
</script>

<style scoped>
.n8n-chat-container {
  width: 100%;
  height: 100%;
  min-height: 600px;
  position: relative;
  overflow: hidden;
}

/* 确保 N8N Chat 样式正确应用 */
:deep(.n8n-chat) {
  width: 100%;
  height: 100%;
  border-radius: 0.75rem;
  overflow: hidden;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
}

:deep(.n8n-chat-window) {
  border-radius: 0.75rem;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

:deep(.n8n-chat-messages) {
  max-height: none;
  overflow-y: auto;
  padding: 2rem;
  background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
}

:deep(.n8n-chat-input) {
  border-radius: 1.25rem;
  border: 1px solid #e2e8f0;
  background: #f8fafc;
  transition: all 0.2s ease;
}

:deep(.n8n-chat-input:focus) {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
  background: white;
}

/* 确保自定义样式优先级 */
:deep(.n8n-chat *) {
  box-sizing: border-box;
}

/* 响应式优化 */
@media (max-width: 768px) {
  .n8n-chat-container {
    min-height: 500px;
  }
  
  :deep(.n8n-chat-messages) {
    padding: 1.5rem;
  }
}
</style>
